<!--
 * @Description: 服务分类
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2023-05-09 14:18:46
 * @LastEditTime: 2023-05-09 18:05:07
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
	<div class="lb-service-classify">
		<top-nav />
		<div class="page-main">
			<el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="listForm"
        >
		  <el-form-item label="等级" prop="admin_id">
		    <el-select
		      @change="levelChange"
		      v-model="searchForm.level"
		      placeholder="请选择等级"
		      filterable
		      clearable
		    >
		    <el-option
		        v-for="item in levelList"
		        :key="item.id"
		        :label="item.name"
		        :value="item.id"
		      ></el-option>
		    </el-select>
      </el-form-item>
	  <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('list')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
			<el-row class="page-top-operate">
				<lb-button size="medium" type="primary" icon="el-icon-plus" @click="toShowDialog"
					v-hasPermi="`${$route.name}-add`">{{ $t('menu.ShopClassifyAdd') }}</lb-button>
			</el-row>
			<el-table v-loading="loading" :data="tableData"
				:header-cell-style="{ background: '#f5f7fa', color: '#606266' }" style="width: 100%">
				<el-table-column prop="id" label="ID"></el-table-column>
				<el-table-column prop="parent.title" label="一级分类"></el-table-column>
				<el-table-column prop="title" label="分类名"></el-table-column>
				<el-table-column prop="cover" label="封面图">
					<template slot-scope="scope">
						<lb-image :src="scope.row.cover" />
					</template>
				</el-table-column>
				<el-table-column prop="top" label="排序值"></el-table-column>
				<el-table-column prop="status" label="是否上架">
					<template slot-scope="scope">
						<el-switch :disabled="
                $route.meta.pagePermission[0].auth.includes('edit')
                  ? false
                  : true
              " v-model="scope.row.status" :active-value="1" :inactive-value="0"
							@change="updateItem(scope.row.id, scope.row.status)">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="是否首页展示">
					<template slot-scope="scope">
						<el-switch :disabled="
		        $route.meta.pagePermission[0].auth.includes('edit')
		          ? false
		          : true
		      " v-model="scope.row.index_switch" :active-value="1" :inactive-value="0"
							@change="updateIndex(scope.row.id, scope.row.index_switch)">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						<p>{{ scope.row.create_time | handleTime(1) }}</p>
						<p>{{ scope.row.create_time | handleTime(2) }}</p>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="120">
					<template slot-scope="scope">
						<div class="table-operate">
							<lb-button size="mini" plain type="primary" @click="toShowDialog(scope.row.id)"
								v-hasPermi="`${$route.name}-edit`">{{ $t('action.edit') }}</lb-button>
							<lb-button size="mini" plain type="danger" @click="confirmDel(scope.row.id, -1)"
								v-hasPermi="`${$route.name}-delete`">{{ $t('action.delete') }}</lb-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<lb-page :batch="false" :page="searchForm.page" :pageSize="searchForm.limit" :total="total"
				@handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
			</lb-page>
		</div>
		<el-dialog :title="
        $t(subForm.id ? 'menu.ShopClassifyEdit' : 'menu.ShopClassifyAdd')
      " :visible.sync="showDialog" width="500px" center>
			<el-form class="dialog-form" :model="subForm" ref="subForm" :rules="subFormRules" label-width="100px">
				<el-form-item label="分类等级" prop="title">
					<el-radio-group v-model="subForm.level" @input="getTypeList()">
						<el-radio :label="1">一级分类</el-radio>
						<el-radio :label="2">二级分类</el-radio>
						<el-radio :label="3">三级分类</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="上级分类" prop="title" v-if="subForm.level == '2'">
					<el-select v-model="subForm.pid" placeholder="请选择上级分类" required>
						<el-option v-for="item in firstlist" :key="item.id" :label="item.title" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级分类" prop="title" v-if="subForm.level == '3'">
					<el-cascader style="width: 300px;" v-model="subForm.pid" :options="firstlist" @change="handleChange" :props="{ value: 'id', label: 'title' }"></el-cascader>
				</el-form-item>
				<el-form-item label="分类名" prop="title">
					<el-input v-model="subForm.title" maxlength="5" show-word-limit placeholder="请输入分类名"></el-input>
				</el-form-item>
				<el-form-item label="封面图" prop="cover">
					<lb-cover :fileList="subForm.cover" @selectedFiles="getCover"></lb-cover>
					<lb-tool-tips>图片建议尺寸: 200 * 200</lb-tool-tips>
				</el-form-item>
				<el-form-item label="排序值" prop="top">
					<el-input-number class="lb-input-number" :min="0" :controls="false" v-model="subForm.top"
						placeholder="请输入排序值"></el-input-number>
					<lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showDialog = false">取 消</el-button>
				<el-button type="primary" @click="submitFormInfo" v-preventReClick>确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import moment from 'moment'
	export default {
		data() {
			return {
				levelList:[
				{
					id:'1',
					name:'一级分类'
				},
				{
					id:'2',
					name:'二级分类'
				},
				{
					id:'3',
					name:'三级分类'
				},
			],
			searchList:{
				level:''
			},
				loading: false,
				searchForm: {
					page: 1,
					limit: 10
				},
				tableData: [],
				total: 0,
				showDialog: false,
				dialogTitle: true,
				subForm: {
					id: 0,
					title: '',
					cover: [],
					top: 0,
					level:'1',
					pid:0
				},
				subFormRules: {
					pid:'',
					type:2,
					title: {
						required: true,
						validator: this.$reg.isNotNull,
						text: '分类名',
						reg_type: 2,
						trigger: 'blur'
					},
					cover: {
						required: true,
						type: 'array',
						message: '请上传图片',
						trigger: ['blur', 'change']
					},
					top: {
						required: true,
						type: 'number',
						message: '请输入排序值',
						trigger: 'blur'
					},
				},
				form: {
					selectValue: ''
				},
				firstlist: [],
			}
		},
		created() {
			this.getTableDataList()
			this.getTypeList()
		},
		methods: {
			resetForm (form) {
    			this.searchForm.level = "";
      			this.getTableDataList(1)
			},
			levelChange(){
				this.getTableDataList(1)
			},
			handleChange(e){
			
			this.subForm.pid = e[1]
			console.log(this.subForm.pid ,'22222222222222');
		},
			getTypeList() {
			let level = this.subForm.level - 1
			this.$api.service.lastCate({
				level: level,
				type: 2
			}).then(res => {
				if (res.code == 200) {
					this.firstlist = res.data
				}
			})
		},
			handleSizeChange(val) {
				this.searchForm.limit = val
				this.handleCurrentChange(1)
			},
			handleCurrentChange(val) {
				this.searchForm.page = val
				this.getTableDataList()
			},
			getCover(img) {
				this.subForm.cover = img
			},
			async toShowDialog(id = 0) {
				let item = {
					id,
					title: '',
					cover: [],
					top: 0
				}
				if (id) {
					let {
						data
					} = await this.$api.service.cateInfo({
						id
					})
					data.cover = [{
						url: data.cover
					}]
					item = data
					this.subForm.pid = data.pid
				}
				for (let key in this.subForm) {
					this.subForm[key] = item[key]
				}
				this.showDialog = true
			},
			async getTableDataList(flag) {
				if (flag) this.searchForm.page = 1
				this.searchForm.type = 2
				this.tableData = []
				this.loading = true
				let {
					searchForm
				} = this
				let {
					code,
					data
				} = await this.$api.service.cateList(searchForm)
				this.loading = false
				if (code !== 200) return
				console.log(data)
				this.tableData = data.data
				this.total = data.total
			},
			confirmDel(id, status) {
				this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
					confirmButtonText: this.$t('action.comfirm'),
					cancelButtonText: this.$t('action.cancel'),
					type: 'warning'
				}).then(() => {
					this.updateItem(id, status)
					this.updateIndex(id, index_switch)
				}).catch(() => {

				})
			},
			async updateItem(id, status) {
				this.$api.service.cateUpdate({
					id,
					status
				}).then(res => {
					if (res.code === 200) {
						this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
						if (status === -1) {
							this.searchForm.page = this.searchForm.page < Math.ceil((this.total - 1) / this
								.searchForm.limit) ? this.searchForm.page : Math.ceil((this.total - 1) /
								this.searchForm.limit)
							this.getTableDataList()
						}
					} else {
						if (status === -1) return
						this.getTableDataList()
					}
				})
			},
			async updateIndex(id,index_switch){
				this.$api.service.cateUpdate({
					id,
					index_switch
				}).then(res => {
					if (res.code === 200) {
						this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
						if (status === -1) {
							this.searchForm.page = this.searchForm.page < Math.ceil((this.total - 1) / this
								.searchForm.limit) ? this.searchForm.page : Math.ceil((this.total - 1) /
								this.searchForm.limit)
							this.getTableDataList()
						}
					} else {
						if (status === -1) return
						this.getTableDataList()
					}
				})
			},
			async submitFormInfo() {
				this.subForm.type = 2
				console.log(this.subForm)
				let flag = true
				this.$refs['subForm'].validate(valid => {
					if (!valid) flag = false
				})
				if (flag) {
					let subForm = JSON.parse(JSON.stringify(this.subForm))
					subForm.cover = subForm.cover[0].url
					let methodModel = subForm.id ? 'cateUpdate' : 'cateAdd'
					let {
						code
					} = await this.$api.service[methodModel](subForm)
					if (code !== 200) return
					this.$message.success(this.$t('tips.successSub'))
					this.showDialog = false
					this.getTableDataList()
				}
			}
		},
		filters: {
			handleTime(val, type) {
				let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format(
					'HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
				return time
			}
		}
	}
</script>

<style lang="scss" scoped>
	.dialog-form {

		.el-input,
		.el-select,
		.el-input-number {
			width: 300px;
		}
	}
</style>